<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
  </head>
  <body>
    <script>
      //案例 1
      function timeout(ms) {
        return new Promise((resolve) => {
          console.log('开启定时');
          setTimeout(() => {
            console.log('结束定时');
            resolve('ok');
          }, ms);
        });
      }
      async function asyncPrint(value, ms) {
        let result = await timeout(ms);//由于timeout内是异步任务，不会阻塞async函数外的代码
        // 阻塞2s timeout中有2s的定时器 2s后resolve('ok'); 下面开始执行
        // 也可以通过.then 去执行下面的两行代码
        console.log("result:",result);
        console.log("value:",value);//会被await阻塞，await返回后才执行
      }
      asyncPrint('world', 2000);
      // 不阻塞
      console.log('hello ');
      //开启定时
      // hello
      
      // 结束定时
      // result: ok
      // value: world


      //案例2
      function sleep(ms) {
        //延时作用，同步任务
        var start = new Date();
        while (new Date() - start <= ms) {}
      }
      async function asyncPrint(value, ms) {
        let result = await sleep(ms);//sleep内是同步任务，会阻塞async函数外的代码
        console.log(result);
        console.log(value);//会被await阻塞，await返回后才执行
      }
      asyncPrint('hello world', 2000);
      console.log('hello');

      // 外面也会被阻塞
      // 2s后
      // hello
      // hello world

    </script>
  </body>
</html>
